package com.gfxy.common.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gfxy.common.portal.entity.SysLoginUser;
import com.gfxy.common.portal.entity.SysOrganization;
import com.gfxy.common.portal.entity.SysRole;
import com.gfxy.common.portal.service.OrganizationService;
import com.gfxy.common.portal.service.RoleResourceService;
import com.gfxy.common.portal.service.RoleService;
import com.gfxy.common.portal.service.UserService;
import com.gfxy.commons.message.Message;
import com.gfxy.commons.message.MessageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author: lijixin 2019-05-31
 */
@Controller
@RequestMapping("loginUser")
public class LoginUserController {

    private static final Logger logger = LoggerFactory.getLogger(LoginUserController.class);

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleResourceService roleResourceService;

    @Autowired
    private RoleService roleService;

    @RequestMapping("/index.action")
    public String handleRequest(HttpServletRequest request){
        return "base/system/loginUser";
    }


    @RequestMapping(value = "/getGroupInfoWithUser", method = RequestMethod.GET)
    public @ResponseBody
    JSONArray getGroupInfoWithUser(HttpServletRequest request) {

        String organizationId = request.getParameter("organizationId");
        String level = request.getParameter("level");
        if(organizationId == null ){
            List<SysOrganization> organizations = organizationService.findAll();
            JSONArray result = this.addIsParent(organizations);
            System.out.println(result);
            return result;
        } else {
            List<SysOrganization> organizations = organizationService.findAllByParentId(organizationId);
            JSONArray result = this.addIsParent(organizations);
            System.out.println(result);
            return result;
        }
    }

    @RequestMapping(value = "/getUserList", method = RequestMethod.GET)
    public @ResponseBody
    List<Map> getUserTablelList(HttpServletRequest request) {
        String deptId = request.getParameter("deptId");
        return userService.findUserByDeptId(deptId);
    }

    private JSONArray addIsParent(Iterable<SysOrganization> it){
        JSONArray result = new JSONArray();
        Iterator<SysOrganization> iterator = it.iterator();
        while(iterator.hasNext()){
            SysOrganization organization = iterator.next();
            String jsonStr = JSONObject.toJSONString(organization);

            JSONObject object = JSONObject.parseObject(jsonStr);
            object.put("isParent", "true");

            result.add(object);
        }
        return result;
    }

    @RequestMapping(value = "/saveUserInfoData" ,method = RequestMethod.POST)
    public @ResponseBody Message saveUserInfoData(HttpServletRequest request){
        String userId = request.getParameter("userId");
        String name = request.getParameter("name");
        String loginName = request.getParameter("loginName");

        String organization = request.getParameter("organization");
        String state = request.getParameter("state");

        SysLoginUser user = new SysLoginUser();
        user.setLoginName(loginName);
        user.setCnName(name);
        user.setOrganizationId(organization);
        user.setState(Integer.parseInt(state));
        user.setUserId(userId);
        logger.info("保存用户：[" + user + "]");
        if(userId==null|| userId.isEmpty()){
            //新增
            try {
                userService.addUser(user);

                roleResourceService.addDefaultRoleUser(user);
            } catch (NoSuchAlgorithmException e) {
                return MessageUtil.getErrorMsg(e.getMessage());
            }
        } else {
            userService.updateUser(user);
        }
        return MessageUtil.getSuccessMsg("成功");
    }

    @RequestMapping(value = "/delUserInfoData", method = RequestMethod.POST)
    public @ResponseBody Message delUserInfoData(HttpServletRequest request){
        String userId = request.getParameter("userId");

        logger.info("删除用户：[" + userId + "]");
        userService.deleteUser(userId);
        return MessageUtil.getSuccessMsg("成功");
    }

    /**
     * 重置密码
     * @param request
     * @return
     */
    @RequestMapping(value = "/reSetUserPwd", method = RequestMethod.POST)
    public @ResponseBody Message reSetUserPwd(HttpServletRequest request){
        String userId = request.getParameter("userId");

        logger.info("重置用户：[" + userId + "] 的密码");
        try {
            userService.reSetUserPwd(userId);
        } catch (NoSuchAlgorithmException e) {
            logger.error("重置密码失败。" , e);
            MessageUtil.getSuccessMsg("重置密码失败：" + e.getMessage());
        }
        return MessageUtil.getSuccessMsg("成功");
    }

    /**
     * 获取用户角色
     * @param request
     * @return
     */
    @RequestMapping(value = "/getUserRole" ,method = RequestMethod.GET)
    public @ResponseBody JSONObject getUserRole(HttpServletRequest request){
        String userId = request.getParameter("userId");

        JSONObject rtMsg = new JSONObject();
        List<SysRole> selectedList = roleService.getUserRole(userId);
        List<SysRole> nonSelectedList = roleService.getUserNoRole(userId);

        JSONArray selected = JSONArray.parseArray(JSONObject.toJSONString(selectedList));
        JSONArray nonSelected = JSONArray.parseArray(JSONObject.toJSONString(nonSelectedList));
        JSONObject message = new JSONObject();
        message.put("selected",selected);
        message.put("nonSelected",nonSelected);
        rtMsg.put("success",true);
        rtMsg.put("message",message);
        return rtMsg;
    }

    @RequestMapping(value = "/saveUserRole" ,method = RequestMethod.POST)
    public @ResponseBody Message saveUserRole(HttpServletRequest request){
        String userId = request.getParameter("userId");
        String roleSelectData = request.getParameter("roleSelectData");
        roleResourceService.deleteUserRole(userId);
        int resultInt = roleResourceService.addUserRoles(userId,roleSelectData);
        Message result = MessageUtil.getSuccessMsg(resultInt);
        return result;
    }


    /**
     * 检查用户是否唯一
     * @param request
     * @return
     */
    @RequestMapping(value = "/checkLoginNameUnique", method = RequestMethod.GET)
    public @ResponseBody
    JSONObject checkLoginNameUnique(HttpServletRequest request) {
        JSONObject rt = new JSONObject();
        rt.put("valid", false);

        String loginName = request.getParameter("loginName");

        List<SysLoginUser> loginUser = userService.findUserByLoginName(loginName);
        if(loginUser==null|| loginUser.size()==0){
            rt.put("valid", true);
        } else {
            rt.put("valid", false);
        }
        return rt;
    }
}
